// 全局变量
let groups = [];
let groupCounter = 0;
let socket = null;
let currentTaskId = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    // 连接Socket.IO
    socket = io();
    
    socket.on('connect', function() {
        console.log('WebSocket connected');
    });
    
    socket.on('progress_update', function(data) {
        handleProgressUpdate(data);
    });
    
    socket.on('disconnect', function() {
        console.log('WebSocket disconnected');
    });
    
    // 初始化3个空大组
    for (let i = 0; i < 3; i++) {
        addGroup();
    }
});

// 添加大组
function addGroup() {
    groupCounter++;
    const groupId = `group-${groupCounter}`;
    
    const group = {
        id: groupId,
        name: `大组${groupCounter}`,
        testFiles: [],
        answerFiles: []
    };
    
    groups.push(group);
    renderGroup(group);
}

// 渲染大组
function renderGroup(group) {
    const container = document.getElementById('groups-container');
    
    const groupHtml = `
        <div class="group-card" id="${group.id}">
            <div class="group-header">
                <input type="text" class="form-control" style="max-width: 300px;" 
                       value="${group.name}" 
                       onchange="updateGroupName('${group.id}', this.value)"
                       placeholder="大组名称">
                <button class="btn btn-danger btn-sm" onclick="removeGroup('${group.id}')">
                    <span>🗑️</span> 删除
                </button>
            </div>
            <div class="group-body">
                <div class="row">
                    <div class="col-md-6">
                        <h6>测试组文件</h6>
                        <div class="file-upload-area" 
                             id="${group.id}-test-upload"
                             onclick="document.getElementById('${group.id}-test-input').click()"
                             ondrop="handleDrop(event, '${group.id}', 'test')"
                             ondragover="handleDragOver(event)"
                             ondragleave="handleDragLeave(event)">
                            <div>📁 点击或拖拽文件到这里</div>
                            <div style="font-size: 12px; color: #6c757d; margin-top: 5px;">支持多文件上传</div>
                        </div>
                        <input type="file" 
                               id="${group.id}-test-input" 
                               style="display: none;" 
                               multiple
                               onchange="handleFileSelect(event, '${group.id}', 'test')">
                        <div id="${group.id}-test-list" class="file-list"></div>
                    </div>
                    <div class="col-md-6">
                        <h6>答案组文件</h6>
                        <div class="file-upload-area" 
                             id="${group.id}-answer-upload"
                             onclick="document.getElementById('${group.id}-answer-input').click()"
                             ondrop="handleDrop(event, '${group.id}', 'answer')"
                             ondragover="handleDragOver(event)"
                             ondragleave="handleDragLeave(event)">
                            <div>📁 点击或拖拽文件到这里</div>
                            <div style="font-size: 12px; color: #6c757d; margin-top: 5px;">支持多文件上传</div>
                        </div>
                        <input type="file" 
                               id="${group.id}-answer-input" 
                               style="display: none;" 
                               multiple
                               onchange="handleFileSelect(event, '${group.id}', 'answer')">
                        <div id="${group.id}-answer-list" class="file-list"></div>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', groupHtml);
}

// 更新大组名称
function updateGroupName(groupId, newName) {
    const group = groups.find(g => g.id === groupId);
    if (group) {
        group.name = newName;
    }
}

// 删除大组
function removeGroup(groupId) {
    if (confirm('确定要删除这个大组吗？')) {
        groups = groups.filter(g => g.id !== groupId);
        document.getElementById(groupId).remove();
    }
}

// 处理拖拽
function handleDragOver(event) {
    event.preventDefault();
    event.currentTarget.classList.add('drag-over');
}

function handleDragLeave(event) {
    event.currentTarget.classList.remove('drag-over');
}

function handleDrop(event, groupId, type) {
    event.preventDefault();
    event.currentTarget.classList.remove('drag-over');
    
    const files = event.dataTransfer.files;
    uploadFiles(files, groupId, type);
}

// 处理文件选择
function handleFileSelect(event, groupId, type) {
    const files = event.target.files;
    uploadFiles(files, groupId, type);
}

// 上传文件
async function uploadFiles(files, groupId, type) {
    if (files.length === 0) return;
    
    const formData = new FormData();
    for (let file of files) {
        formData.append('files', file);
    }
    
    try {
        const response = await fetch('/api/upload_files', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            const group = groups.find(g => g.id === groupId);
            if (group) {
                if (type === 'test') {
                    group.testFiles.push(...result.files);
                } else {
                    group.answerFiles.push(...result.files);
                }
                renderFileList(groupId, type);
            }
        } else {
            alert('文件上传失败: ' + result.error);
        }
    } catch (error) {
        alert('文件上传失败: ' + error.message);
    }
}

// 渲染文件列表
function renderFileList(groupId, type) {
    const group = groups.find(g => g.id === groupId);
    if (!group) return;
    
    const files = type === 'test' ? group.testFiles : group.answerFiles;
    const listElement = document.getElementById(`${groupId}-${type}-list`);
    
    listElement.innerHTML = '';
    
    files.forEach((file, index) => {
        const displayName = file.split('_').slice(1).join('_') || file; // 移除时间戳前缀
        const fileHtml = `
            <div class="file-item">
                <span class="file-name" title="${displayName}">${displayName}</span>
                <button class="remove-file-btn" onclick="removeFile('${groupId}', '${type}', ${index})">删除</button>
            </div>
        `;
        listElement.insertAdjacentHTML('beforeend', fileHtml);
    });
}

// 删除文件
function removeFile(groupId, type, index) {
    const group = groups.find(g => g.id === groupId);
    if (group) {
        if (type === 'test') {
            group.testFiles.splice(index, 1);
        } else {
            group.answerFiles.splice(index, 1);
        }
        renderFileList(groupId, type);
    }
}

// 开始测试
async function startTest() {
    // 验证数据
    const validGroups = groups.filter(g => g.testFiles.length > 0 && g.answerFiles.length > 0);
    
    if (validGroups.length === 0) {
        alert('请至少添加一个包含测试文件和答案文件的大组！');
        return;
    }
    
    if (!confirm(`即将开始测试 ${validGroups.length} 个大组，是否继续？`)) {
        return;
    }
    
    // 准备数据
    const groupsData = validGroups.map(g => ({
        name: g.name,
        test_files: g.testFiles,
        answer_files: g.answerFiles
    }));
    
    // 显示进度区域
    document.getElementById('progress-section').style.display = 'block';
    document.getElementById('result-section').style.display = 'none';
    document.getElementById('progress-log').innerHTML = '';
    
    try {
        const response = await fetch('/api/start_test', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                groups: groupsData
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            currentTaskId = result.task_id;
            addLogEntry('测试任务已启动，任务ID: ' + currentTaskId);
        } else {
            alert('启动测试失败: ' + result.error);
        }
    } catch (error) {
        alert('启动测试失败: ' + error.message);
    }
}

// 处理进度更新
function handleProgressUpdate(data) {
    if (data.task_id !== currentTaskId) return;
    
    const progressBar = document.getElementById('progress-bar');
    const progressMessage = document.getElementById('progress-message');
    
    progressBar.style.width = data.progress + '%';
    progressBar.textContent = data.progress + '%';
    progressMessage.textContent = data.message;
    
    addLogEntry(data.message);
    
    if (data.status === 'completed') {
        progressBar.classList.remove('progress-bar-animated');
        progressBar.classList.add('bg-success');
        progressMessage.classList.remove('alert-info');
        progressMessage.classList.add('alert-success');
        
        // 显示报告
        document.getElementById('result-section').style.display = 'block';
        document.getElementById('report-content').innerHTML = data.html_report;
    } else if (data.status === 'error') {
        progressBar.classList.remove('progress-bar-animated');
        progressBar.classList.add('bg-danger');
        progressMessage.classList.remove('alert-info');
        progressMessage.classList.add('alert-danger');
        
        // 显示详细错误信息
        if (data.detailed_error) {
            addLogEntry('=== 详细错误信息 ===', 'error');
            const errorLines = data.detailed_error.split('\n');
            errorLines.forEach(line => {
                if (line.trim()) {
                    addLogEntry(line, 'error');
                }
            });
        }
    }
}

// 添加日志条目
function addLogEntry(message, type = 'info') {
    const logContainer = document.getElementById('progress-log');
    const timestamp = new Date().toLocaleTimeString();
    
    let logClass = 'log-entry';
    let textColor = '#333';
    let borderColor = '#0d6efd';
    
    if (type === 'error') {
        logClass += ' log-error';
        textColor = '#dc3545';
        borderColor = '#dc3545';
    } else if (type === 'warning') {
        logClass += ' log-warning';
        textColor = '#fd7e14';
        borderColor = '#fd7e14';
    } else if (type === 'success') {
        logClass += ' log-success';
        textColor = '#198754';
        borderColor = '#198754';
    }
    
    const logHtml = `
        <div class="${logClass}" style="border-left-color: ${borderColor};">
            <span style="color: #6c757d;">[${timestamp}]</span> 
            <span style="color: ${textColor};">${message}</span>
        </div>
    `;
    logContainer.insertAdjacentHTML('beforeend', logHtml);
    logContainer.scrollTop = logContainer.scrollHeight;
}

// 下载Excel报告
async function downloadExcel() {
    console.log('[DEBUG] 下载Excel报告，当前任务ID:', currentTaskId);
    
    if (!currentTaskId) {
        alert('没有可用的报告，当前任务ID为空');
        return;
    }
    
    try {
        // 先检查任务状态
        const statusResponse = await fetch(`/api/task_status/${currentTaskId}`);
        const statusResult = await statusResponse.json();
        
        console.log('[DEBUG] 任务状态检查结果:', statusResult);
        
        if (!statusResult.success) {
            alert(`任务状态检查失败: ${statusResult.error}\n可用任务: ${statusResult.available_tasks?.join(', ') || '无'}`);
            return;
        }
        
        if (statusResult.status !== 'completed') {
            alert(`任务尚未完成，当前状态: ${statusResult.status}`);
            return;
        }
        
        if (!statusResult.has_excel) {
            alert('Excel报告文件不存在');
            return;
        }
        
        // 任务状态正常，开始下载
        console.log('[DEBUG] 跳转到下载链接:', `/api/download_report/${currentTaskId}`);
        window.location.href = `/api/download_report/${currentTaskId}`;
        
    } catch (error) {
        console.error('[ERROR] 检查任务状态失败:', error);
        alert('检查任务状态失败: ' + error.message);
    }
}


